Don't create a mutexattr for each mutex
authorMukund Sivaraman <muks@banu.com>
Wed, 22 Apr 2015 08:10:06 +0000 (13:40 +0530)
committerMukund Sivaraman <muks@banu.com>
Thu, 23 Apr 2015 14:41:02 +0000 (20:11 +0530)
babl/babl-mutex.c

index 708c54a7074d67729f33f6ed1abd98d613307671..4fa5f29b0d6a14677b8f245533aaaf5114d3df48 100644 (file)
 
 #include <stdlib.h>
 
+#ifndef _WIN32
+
+static const pthread_mutexattr_t *
+get_mutex_attr (void)
+{
+  static pthread_mutexattr_t mutexattr;
+  static int initialized = 0;
+
+  if (!initialized)
+    {
+      /* On some platforms, this will keep an allocation till process
+         termination, but it isn't a growing leak. */
+      pthread_mutexattr_init (&mutexattr);
+      pthread_mutexattr_settype (&mutexattr, PTHREAD_MUTEX_RECURSIVE);
+      initialized = 1;
+    }
+
+  return &mutexattr;
+}
+
+#endif
+
 BablMutex  *
 babl_mutex_new (void)
 {
@@ -28,12 +50,7 @@ babl_mutex_new (void)
 #ifdef _WIN32
   InitializeCriticalSection (mutex);
 #else
-  pthread_mutexattr_t mutexattr;
-
-  pthread_mutexattr_init (&mutexattr);
-  pthread_mutexattr_settype (&mutexattr, PTHREAD_MUTEX_RECURSIVE);
-  pthread_mutex_init (mutex, &mutexattr);
-  pthread_mutexattr_destroy (&mutexattr);
+  pthread_mutex_init (mutex, get_mutex_attr ());
 #endif
   return mutex;
 }